package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojo.ApBehaviorEntry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author by jojo
 * @Date 2022/3/8
 * @Description
 */
@Service
@Slf4j
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询行为实体
     *
     * @param userId      用户id
     * @param equipmentId 设备id
     * @return
     */
    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        if (userId != null) {
            //用户id不为空，先用用户id查，type类型=1（用户id）
            Query query = Query.query(Criteria.where("refId").is(userId)
                    .and("type").is(ApBehaviorEntry.Type.USER.getCode()));
            ApBehaviorEntry one = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            //如果不存在基于userId创建实体数据
            //        返回行为实体
            if (one==null) {
                ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
                apBehaviorEntry.setRefId(userId);
                apBehaviorEntry.setType((short)1);
                apBehaviorEntry.setCreatedTime(new Date());
                one = mongoTemplate.save(apBehaviorEntry);
            }
            return one;
        }else {
            //用户id为空，用设备id查，type 类型=0 （设备id）
            Query query = Query.query(Criteria.where("refId").is(equipmentId)
                    .and("type").is(ApBehaviorEntry.Type.EQUIPMENT.getCode()));
            ApBehaviorEntry one = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            // 如果不存在基于设备id创建实体数据
            //        返回行为实体
            if (one==null) {
                ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
                apBehaviorEntry.setRefId(equipmentId);
                apBehaviorEntry.setType((short)0);
                apBehaviorEntry.setCreatedTime(new Date());
                one = mongoTemplate.save(apBehaviorEntry);
            }
            return one;
        }
    }
}
